<template>
  <page-view avatar="" :title="false" :header-disabled="true">
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="角色名称/描述">
                <a-input placeholder="请输入" v-model="queryParam.searchWord"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select placeholder="请选择" v-model="queryParam.status">
                  <a-select-option value="-1">全部</a-select-option>
                  <a-select-option value="1">正常</a-select-option>
                  <a-select-option value="0">禁用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="search">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-page-operator-wrapper">
        <a-button @click="$refs.roleEditPanel.show()" type="primary" v-hasPermission="'sys:role:save'" ghost>新增</a-button>
        <a-button v-hasPermission="'sys:role:delete'" @click="batchDelete(selectedRowKeys)" :disabled="selectedRowKeys.length === 0">删除</a-button>
        <a-dropdown v-hasPermission="'sys:role:export'">
          <a-menu slot="overlay">
            <a-menu-item key="export-data" @click="exprotExccel">导出Excel</a-menu-item>
          </a-menu>
          <a-button>
            更多操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>
      <s-table
        ref="table"
        :columns="columns"
        :data="loadData"
        rowKey="id"
        :row-selection="rowSelection"
      >
        <div
          slot="expandedRowRender"
          slot-scope="record"
          style="margin: 0">
          <resource-panel @add-action="$refs.roleEditPanel.show(record)" :resourceIds="record.resourceIds || []" action-name="sys:role:update"/>
        </div>
        <span slot="action" slot-scope="text, record">
          <a @click="$refs.roleEditPanel.show(record)" v-hasPermission="'sys:role:update'">编辑</a>
          <a-divider type="vertical" v-hasPermission="'sys:role:update'"/>
          <a-dropdown>
            <a class="ant-dropdown-link">
              更多 <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href="javascript:;" @click="$refs.roleEditPanel.show(record, true)">详情</a>
              </a-menu-item>
              <a-menu-item v-if="record.status === '1'" v-hasPermission="'sys:role:disabled'">
                <a href="javascript:;" @click="updateStatus(record)">禁用</a>
              </a-menu-item>
              <a-menu-item v-if="record.status === '0'" v-hasPermission="'sys:role:useable'">
                <a href="javascript:;" @click="updateStatus(record)">启用</a>
              </a-menu-item>
              <a-menu-item v-hasPermission="'sys:role:delete'">
                <a href="javascript:;" @click="deleteRecord(record)">删除</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
        <template slot="status" slot-scope="text">
          <a-tag v-if="text === '1'" color="green">
            {{ text | getLabel('sys_role_state') }}
          </a-tag>
          <a-tag v-else-if="text === '0'">
            {{ text | getLabel('sys_role_state') }}
          </a-tag>
        </template>
      </s-table>

      <role-edit-panel ref="roleEditPanel" @handle-success="formHandleSuccess"/>
    </a-card>
  </page-view>
</template>

<script>
import { PageView } from '@/layouts'
import { STable, DescriptionList } from '@/components'
import RoleEditPanel from './modules/RoleEditPanel'
import ResourcePanel from '@/views/common/ResourcePanel'
import store from '@/store'

const DescriptionListItem = DescriptionList.Item
export default {
  name: 'TableList',
  components: {
    PageView,
    STable,
    DescriptionList,
    DescriptionListItem,
    RoleEditPanel,
    ResourcePanel
  },
  data () {
    return {
      description: '列表使用场景：后台管理中的权限管理以及角色管理，可用于基于 RBAC 设计的角色权限控制，颗粒度细到每一个操作类型。',

      visible: false,

      form: null,
      mdl: {},

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        status: '-1'
      },
      // 表头
      columns: [
        {
          title: '唯一识别码',
          dataIndex: 'roleKey'
        },
        {
          title: '角色名称',
          dataIndex: 'name'
        },
        {
          title: '描述',
          dataIndex: 'description'
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        }, {
          title: '操作',
          width: '150px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.refreshStore()
        const params = Object.assign({}, this.queryParam)
        if (params.status === '-1') {
          delete params.status
        }
        return this.$http.get('/role', {
          params: Object.assign(parameter, params)
        }).then(res => {
          return {
            data: res.page.records,
            pageSize: res.page.limit,
            pageNo: res.page.pageNo,
            totalCount: res.page.total
          }
        })
      },

      selectedRowKeys: [],
      selectedRows: [],
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        },
        onSelect: (record, selected, selectedRows) => {},
        onSelectAll: (selected, selectedRows, changeRows) => {}
      }
    }
  },
  methods: {
    search () {
      this.$refs.table.refresh(true)
    },
    reset () {
      this.queryParam = {
        status: '-1'
      }
      this.$refs.table.refresh(true)
    },
    exprotExccel () {},
    updateStatus (record) {
      const status = record.status === '1' ? '0' : '1'
      this.$http.put('/role/updateStatus', {
        id: record.id,
        status: status
      }).then(res => {
        if (res.data) {
          this.$message.success('操作成功')
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.data || '操作失败')
        }
      })
    },
    deleteRecord (record) {
      const that = this
      this.$confirm({
        title: '警告',
        content: `真的要删除 ${record.name} 吗?`,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          that.handleDelete([record.id], {
            success () {},
            done () {}
          })
        }
      })
    },
    batchDelete (ids) {
      const that = this
      this.$confirm({
        title: '警告',
        content: `真的要删除这 ${ids.length} 类角色吗?`,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          that.handleDelete(ids, {
            success () {},
            done () {}
          })
        }
      })
    },
    handleDelete (ids, callback) {
      if (ids.length > 0) {
        this.$http.delete('role/' + ids.join(',')).then(res => {
          this.$message.success('已成功删除')
          this.$refs.table.refresh()
          if (callback) {
            (typeof callback.done === 'function') && callback.done.call(this)
            if (typeof callback.success === 'function') { callback.success.call(this, res) }
          }
        }).catch(e => {
          if (callback) {
            (typeof callback.done === 'function') && callback.done.call(this)

            if (typeof callback.fail === 'function') { callback.fail.call(this, e) }
          }
        })
      }
    },
    onChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    formHandleSuccess () {
      this.$refs.table.refresh()
    },
    refreshStore () {
      store.dispatch('AllRoles').then(() => {})
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
